﻿using AbstructFactory;
using ADManage.api.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using XF.Common;
using XF.Common.Redis;
using XF.Meeting.DAL;
using XF.Meeting.Entity.CommonEntity;
using XF.Meeting.Entity.CommonEntity.wx;
using XF.Meeting.Entity.CommonEntity.wxupdate;
using XF.Meeting.Entity.DTO;
using XF.Meeting.Entity.Query;
using XF.Meeting.Entity.View;
using static XF.Meeting.Entity.CommonEntity.wxupdate.WechatScheduleUpdate;
using Schedule = XF.Meeting.Entity.CommonEntity.wxupdate.WechatScheduleUpdate.Schedule;

namespace XF.Meeting.Api.Common
{
    public class WyChatHelper: WeChatHelper
    {
        private static readonly string corpid = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["wycorpid"]);
        private static readonly string secret = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["wysecret"]);
        private HttpClientHelper requst = new HttpClientHelper();
       // public new AbsFactoryTE abs = (AbsFactoryTE)AbsFactory.CreateInterface();
        private string ACCESS_TOKEN { get; set; }
        private string RoomACCESS_TOKEN { get; set; }
        public WyChatHelper()
        {
            ACCESS_TOKEN = GetAccessToken(corpid, secret);
            RoomACCESS_TOKEN = GetAccessToken(corpid, secret);
        }
        public new void SendTextMessage(Message message)
        {
            message.agentid = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["wyagentid"]);
            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(message));
        }
        public new string  GetAccessToken(string corpid, string secret)
        {

            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}");
            // Response.Write(response);
            var aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<GetAccessTokenResponse>(response);
            return aaa.access_token;
        }
        public new string GetUserId(string Code)
        {

            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={ACCESS_TOKEN}&code={Code}");
            var aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<GetAccessTokenResponse>(response);
            return aaa.UserId;
        }
        public new string GetUserInfo(string UserId)
        {

            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={ACCESS_TOKEN}&userid={UserId}");
            //  var aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(response);
            return response;
        }
        public new string CreateChatId(WeChat_Chat enity)
        {


            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(new CreateChat
            ()
            {
                name = enity.name,
                owner = enity.owner,
                userlist = enity.userList,
                chatid = enity.chatid
            }));

            return enity.chatid;
        }

        public new string SendMessageForGroup(WeChat_Chat_Msg entity)
        {
            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(new ChatInfo()
            {
                chatid = entity.ChatId,
                msgtype = entity.MsgType,
                safe = 0,
                text = new Text(entity.Msg)
            }
          ));
            return response;
        }
        /// <summary>
        /// 获取部门信息，
        /// </summary>
        /// <param name="id">为0查询全部</param>
        /// <returns></returns>
        public new Task<Departments> GetDepartments(int id = 0)
        {
            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={ACCESS_TOKEN}&id={id}");
            var depList = JsonConvert.DeserializeObject<Departments>(response);
            return Task.FromResult(depList);
        }
        public new Task<userList> GetUserList(int minId, int fetch_child)
        {
            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={ACCESS_TOKEN}&department_id={minId}&fetch_child={fetch_child}");
            var list = JsonConvert.DeserializeObject<userList>(response);
            return Task.FromResult(list);
        }
        public new void SendWxMssage(CRoomPadQuery query, bool isTen = false)
        {
            bool isZhouqi = false;
            var dal = abs.CreateConferenceRoomInterface("pad", "");
            int ID = 0;
            if (query.type == 2)
            {
                var cInfo = dal.getMeetIdBystrBOID(query.strBOID);
                if (cInfo.CycleMeetType > 0)
                {
                    isZhouqi = true;
                }
                else
                {
                    ID = cInfo.CInfoID;
                }
            }
            else
            {
                ID = query.CInfoId;
            }
            if (!isZhouqi)
            {
                if (!dal.IsSendWX(ID, out string error))
                {


                    var res = dal.GetCInfoByID(ID).Result;

                    var list = TableToList.ToList<MeetingInfoSingle>(res);
                    var meetingInfoSingle = list[0];
                    if (meetingInfoSingle.EndTime < DateTime.Now)
                    {
                        return;
                    }
                    meetingInfoSingle.date = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("yyyy-MM-dd");
                    meetingInfoSingle.Begin = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("HH:mm");
                    meetingInfoSingle.End = Convert.ToDateTime(meetingInfoSingle.EndTime).ToString("HH:mm");
                    if (string.IsNullOrEmpty(meetingInfoSingle.CRooms))
                    {
                        meetingInfoSingle.CRooms = meetingInfoSingle.CRoom;
                    }
                    else
                    {
                        meetingInfoSingle.CRooms = meetingInfoSingle.CRoom + "/"+meetingInfoSingle.CRooms;
                        meetingInfoSingle.CRooms = meetingInfoSingle.CRooms.Substring(0, meetingInfoSingle.CRooms.Length - 1);
                    }

                    var msgList = dal.getMeetInfoAndUserPhone(ID, out string StrError);
                    var phoneList = TableToList.ToList<meetIdS>(msgList.Tables[0]);
                    var userlist = phoneList.Select(i => i.Account).ToList();
                    var userr = GetUserString(userlist);
                    var wx = new WyChatHelper();
                    //XXX邀请您参加《XXXXX》会议，时间：2020-07-29 18:40~19:00，地点：XXXX，主持人：XXXX，请准时出席。
                    var msg = new Message(new Text($"{meetingInfoSingle.CoordinatorName}邀请您参加《{meetingInfoSingle.ConferenceTheme}》会议，时间 {meetingInfoSingle.date}  {meetingInfoSingle.Begin}~{meetingInfoSingle.End}，地点：{meetingInfoSingle.CRooms}，主持人：{meetingInfoSingle.HostPersonName}，请准时出席。"), userr);
                    //var msg = new Message(new Text($"请您参加于{meetingInfoSingle.date}，{meetingInfoSingle.Begin}到{meetingInfoSingle.End}，在（{meetingInfoSingle.CRooms}）举行的由（{meetingInfoSingle.HostPersonName}）主持的（{meetingInfoSingle.ConferenceTheme})主题会议，望准时参加!"), userr);
                    wx.SendTextMessage(msg);
                    if (isTen)
                    {
                        dal.updateWxState(ID, out string strError);
                    }
                }
            }



        }
        public  void SendWxMssageForBPM(CRoomPadQuery query, CInfoIds cInfo, bool isTen = false)
        {
            bool isZhouqi = false;
            var dal = abs.CreateConferenceRoomInterface("pad", "");
            int ID = 0;
         
            if (query.type == 2)
            {
                if (cInfo.CycleMeetType > 0)
                {
                    isZhouqi = true;
                }
                else
                {
                    ID = cInfo.CInfoID;
                }
            }
            else
            {
                ID = query.CInfoId;
            }
            if (!isZhouqi)
            {
                if (!dal.IsSendWX(ID, out string error))
                {


                    var res = dal.GetCInfoByID(ID).Result;

                    var list = TableToList.ToList<MeetingInfoSingle>(res);
                    var meetingInfoSingle = list[0];
                    if (meetingInfoSingle.EndTime < DateTime.Now)
                    {
                        return;
                    }
                    meetingInfoSingle.date = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("yyyy-MM-dd");
                    meetingInfoSingle.Begin = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("HH:mm");
                    meetingInfoSingle.End = Convert.ToDateTime(meetingInfoSingle.EndTime).ToString("HH:mm");
                    if (string.IsNullOrEmpty(meetingInfoSingle.CRooms))
                    {
                        meetingInfoSingle.CRooms = meetingInfoSingle.CRoom;
                    }
                    else
                    {
                        meetingInfoSingle.CRooms = meetingInfoSingle.CRoom + "/" + meetingInfoSingle.CRooms;
                        meetingInfoSingle.CRooms = meetingInfoSingle.CRooms.Substring(0, meetingInfoSingle.CRooms.Length - 1);
                    }

                    var msgList = dal.getMeetInfoAndUserPhone(ID, out string StrError);
                    var phoneList = TableToList.ToList<meetIdS>(msgList.Tables[0]);
                    var userlist = phoneList.Select(i => i.Account).ToList();
                    var userr = GetUserString(userlist);

                    //XXX邀请您参加《XXXXX》会议，时间：2020-07-29 18:40~19:00，地点：XXXX，主持人：XXXX，请准时出席。
                    var msg = new Message(new Text($"{meetingInfoSingle.CoordinatorName}邀请您参加《{meetingInfoSingle.ConferenceTheme}》会议，时间 {meetingInfoSingle.date}  {meetingInfoSingle.Begin}~{meetingInfoSingle.End}，地点：{meetingInfoSingle.CRooms}，主持人：{meetingInfoSingle.HostPersonName}，请准时出席。"), userr);
                    //var msg = new Message(new Text($"请您参加于{meetingInfoSingle.date}，{meetingInfoSingle.Begin}到{meetingInfoSingle.End}，在（{meetingInfoSingle.CRooms}）举行的由（{meetingInfoSingle.HostPersonName}）主持的（{meetingInfoSingle.ConferenceTheme})主题会议，望准时参加!"), userr);
                    switch (cInfo.WxType)
                    {
                        case 1:
                            var wx1 = new WeChatHelper();
                            wx1.SendTextMessage(msg);
                            break;
                        case 2:
                            var wx2 = new WyChatHelper();
                            wx2.SendTextMessage(msg);
                            break;
                        default:
                            var wx3 = new WeChatHelper();
                            wx3.SendTextMessage(msg);
                            break;
                    }
                    var wx = new WeChatHelper();
                    wx.SendTextMessage(msg);
                    if (isTen)
                    {
                        dal.updateWxState(ID, out string strError);
                    }
                }
            }



        }
        public new async void SendChnnelMsg(int id)
        {
            var dal = abs.CreateConferenceRoomInterface("pad", "");
            var res = await dal.GetCInfoByID(id);

            var list = TableToList.ToList<MeetingInfoSingle>(res);
            var meetingInfoSingle = list[0];
            if (meetingInfoSingle.EndTime < DateTime.Now)
            {
                return;
            }
            meetingInfoSingle.date = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("yyyy-MM-dd");
            meetingInfoSingle.Begin = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("HH:mm");
            meetingInfoSingle.End = Convert.ToDateTime(meetingInfoSingle.EndTime).ToString("HH:mm");
            if (string.IsNullOrEmpty(meetingInfoSingle.CRooms))
            {
                meetingInfoSingle.CRooms = meetingInfoSingle.CRoom;
            }
            else
            {
                meetingInfoSingle.CRooms = meetingInfoSingle.CRoom + "/" + meetingInfoSingle.CRooms;
                meetingInfoSingle.CRooms = meetingInfoSingle.CRooms.Substring(0, meetingInfoSingle.CRooms.Length - 1);
            }

            var msgList = dal.getMeetInfoAndUserPhone(id, out string StrError);
            var phoneList = TableToList.ToList<meetIdS>(msgList.Tables[0]);
            var userlist = phoneList.Select(i => i.Account).ToList();
            var userr = GetUserString(userlist);
            var wx = new WyChatHelper();
            //XXX邀请您参加《XXXXX》会议，时间：2020-07-29 18:40~19:00，地点：XXXX，主持人：XXXX，请准时出席。
            var msg = new Message(new Text($"已取消:{meetingInfoSingle.CoordinatorName}邀请您参加《{meetingInfoSingle.ConferenceTheme}》会议，时间 {meetingInfoSingle.date}  {meetingInfoSingle.Begin}~{meetingInfoSingle.End}，地点：{meetingInfoSingle.CRooms}，主持人：{meetingInfoSingle.HostPersonName}，此会议已取消请知悉。"), userr);
            //var msg = new Message(new Text($"请您参加于{meetingInfoSingle.date}，{meetingInfoSingle.Begin}到{meetingInfoSingle.End}，在（{meetingInfoSingle.CRooms}）举行的由（{meetingInfoSingle.HostPersonName}）主持的（{meetingInfoSingle.ConferenceTheme})主题会议，望准时参加!"), userr);
            wx.SendTextMessage(msg);
        }
        /// <summary>
        /// 发送会议室视频密码
        /// </summary>
        /// <param name="cinfoId">会议id</param>
        /// <param name="isSign">签到之后，密码生效，预约成功只发送密码</param>
        public new void SendTPwdToCreator(CRoomPadQuery query, bool isSign)

        {
            bool isZhouqi = false;
            var dal = abs.CreateConferenceRoomInterface("pad", "");
            int ID = 0;
            if (query.type == 2)
            {
                var cInfo = dal.getMeetIdBystrBOID(query.strBOID);
                if (cInfo.CycleMeetType > 0)
                {
                    isZhouqi = true;
                }
                else
                {
                    ID = cInfo.CInfoID;
                }
            }
            else
            {
                ID = query.CInfoId;
            }
            if (!isZhouqi)
            {
    
                    var res = dal.GetCInfoPwdByID(ID).Result;
                    var list = TableToList.ToList<MeetRoomPwd>(res);
                    if (list.Count == 0)
                    {
                        return;
                    }
                    var meetingInfoSingle = list[0];
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in list)
                    {
                        sb.Append(item.ConferenceName).Append("视频会议室呼入号为").Append(item.TerminalShort).Append("，进入PIN码为").Append(item.PWD).Append("。");
                    }

                    var wx = new WyChatHelper();

                    if (isSign)
                    {
                        var msg = new Message(new Text($"您预定的《{meetingInfoSingle.ConferenceTheme}》主题会议已签到，视频PIN已生效。{sb}如需呼入其他视频会议室，请联系会议协调人获取PIN码。"), list[0].Account);
                        wx.SendTextMessage(msg);
                    }
                    else
                    {
                        var msg = new Message(new Text($"您预定的《{meetingInfoSingle.ConferenceTheme}》主题会议，PIN码已生成，{sb}如需呼入其他视频会议室，请联系会议协调人获取PIN码。"), list[0].Account);
                        wx.SendTextMessage(msg);
                    }
                
            }


           
            





        }

        public new static string GetUserString(List<string> userList)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in userList)
            {
                //if (string.IsNullOrWhiteSpace(RedisCache.Hash_Get<string>("UserPhone", item)))
                //{
                //    continue;
                //}

                sb.Append(item);
                sb.Append("|");
            }
            sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }
        /// <summary>
        /// 企业微信添加本地会议室
        /// </summary>
        public new void WXMeetingRoomInsert()
        {

            var meetdal = new MeetingDal();
            var dt = meetdal.GetAllMeetingRoom(out string error).Result;
            if (string.IsNullOrEmpty(error))
            {
                var list = TableToList.ToList<AllRoom>(dt);
                if (list != null && list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        WXMeetingRoom room = new WXMeetingRoom();
                        room.name = item.ConferenceName;
                        room.capacity = item.HoldNumber;
                        //room.building  = item.RegionalName;
                        var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/oa/meetingroom/add?access_token={RoomACCESS_TOKEN}", JsonConvert.SerializeObject(room));
                        var res = Newtonsoft.Json.JsonConvert.DeserializeObject<WXMeetingRoomResponse>(response);
                        if (res.errmsg == "ok")
                        {
                            meetdal.UpdateRoomWXID(item.ID, res.meetingroom_id, out error);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 推送企业微信日程
        /// </summary>
        /// <param name="ID"></param>
        public new void InsertWechatSchedule( int ID)
        {
            var meetdal = new MeetingDal();
            var dal = abs.CreateConferenceRoomInterface("", "");
            WechatSchedule schedule = new WechatSchedule();
            var result = dal.GetCInfoByID(ID).Result;

            var meet = TableToList.ToList<MeetingInfoSingle>(result)[0];
            var msgList = dal.getMeetInfoAndUserPhone(ID, out string StrError);
            var phoneList = TableToList.ToList<meetIdS>(msgList.Tables[0]);
            List<Entity.CommonEntity.wx.Attendees> attendeeslist = new List<Entity.CommonEntity.wx.Attendees>();
            if (phoneList!=null&& phoneList.Count > 0)
            {
                var userlist = phoneList.Select(i => i.Account).ToList();
                var schedulelist = phoneList.DistinctBy(i => i.Account).ToList();
                
                //参会人
                foreach (var item in schedulelist)
                {
                    Entity.CommonEntity.wx.Attendees attendees = new Entity.CommonEntity.wx.Attendees();
                    attendees.userid = item.Account;
                    attendeeslist.Add(attendees);
                }
            }
            Entity.CommonEntity.wx.Schedule scheduleObj = new Entity.CommonEntity.wx.Schedule();
            scheduleObj.attendees = attendeeslist;
            schedule.schedule = scheduleObj;
            schedule.schedule.summary = meet.ConferenceTheme;
            schedule.schedule.description = meet.ConferenceRemark;
            schedule.schedule.location = meet.CRoom+meet.CRooms;
            schedule.schedule.organizer = meet.Creator;
            schedule.schedule.start_time = UnixTimeUtil.DateTimeToUnixTime(meet.BeginTime);
            schedule.schedule.end_time= UnixTimeUtil.DateTimeToUnixTime(meet.EndTime);
            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/oa/schedule/add?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(schedule));
            var res = Newtonsoft.Json.JsonConvert.DeserializeObject<WechatScheduleResponse>(response);
            if (res.errmsg == "ok")
            {

                meetdal.UpdatecCInfoSchedule_id(ID, res.schedule_id,out StrError);
               
            }
        }
        /// <summary>
        /// 更新企业微信日程
        /// </summary>
        /// <param name="ID"></param>
        public new void UpdateWechatSchedule(int ID)
        {
            var meetdal = new MeetingDal();
            var dal = abs.CreateConferenceRoomInterface("", "");
            ScheduleUpdate schedule = new ScheduleUpdate();
            var result = dal.GetCInfoByID(ID).Result;

            var meet = TableToList.ToList<MeetingInfoSingle>(result)[0];
            var msgList = dal.getMeetInfoAndUserPhone(ID, out string StrError);
            var phoneList = TableToList.ToList<meetIdS>(msgList.Tables[0]);
            List<WechatScheduleUpdate.Attendees> attendeeslist = new List<WechatScheduleUpdate.Attendees>();
            if (phoneList!=null&& phoneList.Count > 0)
            {
                var userlist = phoneList.Select(i => i.Account).ToList();
                
                var schedulelist = phoneList.DistinctBy(i => i.Account).ToList();
                //参会人
                foreach (var item in schedulelist)
                {
                    Entity.CommonEntity.wxupdate.WechatScheduleUpdate.Attendees attendees = new Entity.CommonEntity.wxupdate.WechatScheduleUpdate.Attendees();
                    attendees.userid = item.Account;
                    attendeeslist.Add(attendees);
                }
            }
           Schedule scheduleObj = new Schedule();
            scheduleObj.attendees = attendeeslist;
            schedule.schedule = scheduleObj;
            schedule.schedule.summary = meet.ConferenceTheme;
            schedule.schedule.description = meet.ConferenceRemark;
            schedule.schedule.location = meet.CRoom + meet.CRooms;
            schedule.schedule.organizer = meet.Creator;
            schedule.schedule.schedule_id = meet.schedule_id;
            schedule.schedule.start_time = UnixTimeUtil.DateTimeToUnixTime(meet.BeginTime);
            schedule.schedule.end_time = UnixTimeUtil.DateTimeToUnixTime(meet.EndTime);
            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/oa/schedule/update?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(schedule));
            var res = Newtonsoft.Json.JsonConvert.DeserializeObject<WechatScheduleResponse>(response);
            if (res.errmsg == "ok")
            {                

            }
        }
        /// <summary>
        /// 取消企业微信日程
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="schedule_id"></param>
        public new void CancelWechatSchedule(int ID)
        {
            var meetdal = new MeetingDal();
            var dal = abs.CreateConferenceRoomInterface("", "");
            CancelWechatSchedule schedule = new CancelWechatSchedule();
            var result = dal.GetCInfoByID(ID).Result;

            var meet = TableToList.ToList<MeetingInfoSingle>(result)[0];

            schedule.schedule_id = meet.schedule_id;
           
            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/oa/schedule/del?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(schedule));
            var res = Newtonsoft.Json.JsonConvert.DeserializeObject<WechatScheduleResponse>(response);
            if (res.errmsg == "ok")
            {

            }
        }

    }
}
